package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.entity.OperateLogEntity;
import com.xbongbong.paas.log.model.OperateLogModel;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.pro.datawarning.pojo.dto.DataWarningMessageAddDTO;
import com.xbongbong.pro.domain.entity.DataWarningEntity;
import com.xbongbong.pro.domain.entity.DataWarningHistoryEntity;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.WeekEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.ActionTypeEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.DataWarningConditionEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.DataWarningStrategyTypeEnum;
import com.xbongbong.pro.enums.datacenter.datawarning.enums.DwOperationFlagEnum;
import com.xbongbong.pro.enums.errorcodes.ChartErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.ControlCenterMenuEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.statistic.model.DataWarningHistoryModel;
import com.xbongbong.pro.statistic.model.DataWarningModel;
import com.xbongbong.pro.statistic.pojo.ChartInfoDwPojo;
import com.xbongbong.pro.statistic.pojo.DataWarningFieldAttrPojo;
import com.xbongbong.pro.statistic.pojo.DataWarningInChartPojo;
import com.xbongbong.pro.statistic.pojo.DataWarningIndexPojo;
import com.xbongbong.pro.statistic.pojo.DataWarningPojo;
import com.xbongbong.pro.statistic.pojo.DataWarningSavePojo;
import com.xbongbong.pro.statistic.pojo.DataWarningStrategyPojo;
import com.xbongbong.pro.statistic.pojo.DwHistoryDataPojo;
import com.xbongbong.pro.statistic.pojo.DwHistoryDetailsPojo;
import com.xbongbong.pro.statistic.pojo.DwTriggerConditionPojo;
import com.xbongbong.pro.statistic.pojo.dto.ChartListDwDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningBatchDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningDelDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningDetailsDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningEnableDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningGetDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningIndexDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningIndexListDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningListDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningListInChartDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningQueryDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningRemindDTO;
import com.xbongbong.pro.statistic.pojo.dto.DataWarningSaveDTO;
import com.xbongbong.pro.statistic.pojo.dto.DwExecutedRemindDTO;
import com.xbongbong.pro.statistic.pojo.dto.SummaryAttrGetDTO;
import com.xbongbong.pro.statistic.pojo.vo.ChartInfoDwVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningDelVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningEnableVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningGetVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningIndexListVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningIndexVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningListInChartVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningListVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningQueryListVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningQueryVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningRemindVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningSaveVO;
import com.xbongbong.pro.statistic.pojo.vo.DwExecutedRemindVO;
import com.xbongbong.pro.statistic.pojo.vo.DwHistoryListVO;
import com.xbongbong.pro.statistic.pojo.vo.SummaryAttrVO;
import com.xbongbong.pro.statistic.service.ChartService;
import com.xbongbong.pro.statistic.service.DataWarningService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @ClassName DataWarningServiceImpl
 * @Description 数据预警
 * @Author mengna.Deng
 * @Date 2021/4/15 19:49
 * @Version 1.0
 */
@Service("dataWarningService")
public class DataWarningServiceImpl implements DataWarningService {

    private static final Logger LOG = LoggerFactory.getLogger(DataWarningServiceImpl.class);

    @Resource
    private DataWarningModel dataWarningModel;
    @Resource
    private OperateLogModel operateLogModel;
    @Resource
    private DataWarningHistoryModel dataWarningHistoryModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private ChartService chartService;
    @Resource
    BaseProducer baseProducer;
    @Resource
    PackageHelp packageHelp;


    @Override
    public DataWarningListInChartVO list4Chart(DataWarningListInChartDTO listDTO) throws XbbException {
        DataWarningListInChartVO listVO = new DataWarningListInChartVO();
        // 校验，是否是旗舰版
        if (!isUltimate(listDTO.getCorpid())){
            listVO.setHasDataWarningPermission(false);
            listVO.setList(new ArrayList<>());
            return listVO;
        }

        Map<String, Object> param = BeanUtil.convertBean2Map(listDTO);
        param.put(StringConstant.CORPID, listDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.COLUMNS,new StringBuffer("id,name,enable,trigger_condition"));
        param.put("orderByStr","update_time desc");
        List<DataWarningEntity> dataList = dataWarningModel.findEntitys(param);
        List<DataWarningInChartPojo> list = new ArrayList<>();
        try {
            dataList.forEach(item ->{
                List<DwTriggerConditionPojo> triggerConditionPojoList = item.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
                if (CollectionUtils.isNotEmpty(triggerConditionPojoList)){
                    DwTriggerConditionPojo dwTriggerConditionPojo = triggerConditionPojoList.get(0);
                    list.add(new DataWarningInChartPojo(item.getId(),item.getName(),item.getEnable(),dwTriggerConditionPojo.getAttr() + "&"+dwTriggerConditionPojo.getFormId(),triggerConditionPojoList));
                }

            });
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        listVO.setList(list);
        return listVO;
    }

    @Override
    public DataWarningGetVO addOrUpdateGet(DataWarningGetDTO getDTO) throws XbbException {
        DataWarningGetVO dataWarningGetVO = new DataWarningGetVO();
        String corpid = getDTO.getCorpid();
        // 校验，是否是旗舰版
        if (!isUltimate(corpid)){
            return dataWarningGetVO;
        }
        Long id = getDTO.getId();
        Long chartId = getDTO.getChartId();

        // 1.判断新建还是编辑
        DataWarningEntity entity = null;
        if (null != id) {
            entity = dataWarningModel.getByKey(id, corpid);
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
            }
            BeanUtils.copyProperties(entity,dataWarningGetVO);
        }

        // 2.如果是新建判断该图表的数据预警是否超过限制
        if (Objects.nonNull(chartId) && Objects.isNull(getDTO.getId())){
            int count = dataWarningModel.getCountByChartId(chartId,null);
            if (count >= PaasConstant.DATA_WARNING_MAX_CREATE_NUM ){
                throw new XbbException(ChartErrorCodeEnum.API_ERROR_1500001, ChartErrorCodeEnum.API_ERROR_1500001.getMsg());
            }
        }

        // 3.根据chartId和formIdBusinessTypeList获取汇总字段作为触发条件的可选项
        SummaryAttrVO summaryAttrVO = chartService.searchSummaryAttr(new SummaryAttrGetDTO(){{
            setCorpid(getDTO.getCorpid());
            setUserId(getDTO.getUserId());
            setPlatform(getDTO.getPlatform());
            setHttpHeader(getDTO.getHttpHeader());
            setLoginUser(getDTO.getLoginUser());
            setLoginUserName(getDTO.getLoginUserName());
            setChartId(getDTO.getChartId());
            setFormIdBusinessTypeList(getDTO.getFormIdBusinessTypeList());
        }});
        if (Objects.nonNull(summaryAttrVO.getFieldAttrArray()) && summaryAttrVO.getFieldAttrArray().size()>0){
            dataWarningGetVO.setFieldAttrArray(summaryAttrVO.getFieldAttrArray());
        }else {
            dataWarningGetVO.setFieldAttrArray(new ArrayList<>());
        }


        //  加载实际数据
        List<DwTriggerConditionPojo> triggerCondition = new ArrayList<>();
        DataWarningStrategyPojo strategy = new DataWarningStrategyPojo();
        List<OptionalRangeEntity> executor = new ArrayList<>();
        JSONArray action = JSONArray.parseArray(JSON.toJSONString(new ArrayList<Integer>(){{add(ActionTypeEnum.MESSAGE.getCode());}}));
        List<DataWarningFieldAttrPojo> smsExecutor = new ArrayList<>();
        String memo = "";
        String name = entity != null ? entity.getName() : "";
        JSONObject samplingRange = null;

        // 编辑原有表单时加载设置值
        if (entity != null) {
            id = entity.getId();
            triggerCondition = entity.getTriggerCondition().toJavaList(DwTriggerConditionPojo.class);
            if (CollectionUtils.isNotEmpty(triggerCondition)){
                triggerCondition.forEach(item ->{
                    item.setId(item.getAttr() + "&"+item.getFormId());
                    dataWarningGetVO.setTriggerId(item.getAttr() + "&"+item.getFormId());
                } );
            }
            action = entity.getAction();
            strategy = JSONObject.toJavaObject(entity.getStrategy(), DataWarningStrategyPojo.class);
            executor = entity.getExecutor().toJavaList(OptionalRangeEntity.class);
            memo = entity.getMemo();
            samplingRange = entity.getSamplingRange();
        }

        // 执行策略暂时设置默认为1,每天
        if (Objects.isNull(strategy.getStrategyType())){
            strategy.setStrategyType(PaasConstant.DEFAULT_STRATEGY_TYPE);
            strategy.setStrategyTime(PaasConstant.DEFAULT_STRATEGY_TIME);
        }

        // 默认的采集时间范围是8:00-20:00
        if (Objects.isNull(samplingRange)){
            samplingRange = new JSONObject(new HashMap<String,Object>(PaasConstant.DEFAULT_INITIAL_CAPACITY){{put("startTime",PaasConstant.DEFAULT_SIMPLING_RANGE_START);put("endTime",PaasConstant.DEFAULT_SIMPLING_RANGE_END);}});
        }

        // 数据加载
        if (Objects.nonNull(id)){
            dataWarningGetVO.setId(id);
        }
        dataWarningGetVO.setName(name);
        dataWarningGetVO.setTriggerCondition(triggerCondition);
        dataWarningGetVO.setMemo(memo);
        dataWarningGetVO.setAction(action);
        dataWarningGetVO.setStrategy(strategy);
        dataWarningGetVO.setExecutor(executor);
        dataWarningGetVO.setSmsExecutor(smsExecutor);
        dataWarningGetVO.setSamplingRange(samplingRange);
        // 前端需要
        if (Objects.isNull(dataWarningGetVO.getCustomColors())){
            dataWarningGetVO.setCustomColors(new JSONArray());
        }

        // 4.触发条件可选字段条件列表
        dataWarningGetVO.setFieldConditionArray(DataWarningConditionEnum.getDataWarningConditonList());

        // 5.执行设置可选项列表strategy 执行策略，strategyTypeArray、strategyWeekArray
        strategyConditionList(dataWarningGetVO);
        return dataWarningGetVO;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataWarningSaveVO save(DataWarningSaveDTO saveDTO) throws XbbException {
        DataWarningSaveVO dataWarningSaveVO = new DataWarningSaveVO();
        // 校验，是否是旗舰版
        if (!isUltimate(saveDTO.getCorpid())){
            return dataWarningSaveVO;
        }
        String corpid = saveDTO.getCorpid();
        Long id = saveDTO.getId();
        Long chartId = saveDTO.getChartId();
        // TODO 1.参数校验

        // 2.新建保存还是编辑保存
        boolean isAdd = false;
        DataWarningEntity entity = new DataWarningEntity();
        DataWarningEntity oldEntity = new DataWarningEntity();
        if (Objects.isNull(id) || Objects.equals(id,0L)){
            isAdd = true;
            BeanUtil.copyProperties(saveDTO, entity);
        }else {
            oldEntity = dataWarningModel.getByKey(id, corpid);
            if (oldEntity == null) {
                throw new XbbException(ChartErrorCodeEnum.API_ERROR_1500003);
            }
            BeanUtil.copyProperties(saveDTO, entity);
            entity.setUpdateTime((long) DateUtil.getInt());
        }

        // 3.新建判断该图表的数据预警是否超过限制
        if (Objects.nonNull(chartId)){
            int count = dataWarningModel.getCountByChartId(chartId,null);
            if (count >= PaasConstant.DATA_WARNING_MAX_CREATE_NUM && isAdd){
                throw new XbbException(ChartErrorCodeEnum.API_ERROR_1500001,String.format(ChartErrorCodeEnum.API_ERROR_1500001.getMsg(),String.valueOf(PaasConstant.DATA_WARNING_MAX_CREATE_NUM)));
            }
        }

        // 4.触发条件，执行策略，执行人,自定义颜色
        DataWarningStrategyPojo strategyPojo = saveDTO.getStrategy();
        JSONArray triggerCondition = new JSONArray();
        triggerCondition.addAll(saveDTO.getTriggerCondition());
        JSONArray customColors = new JSONArray();
        customColors.addAll(saveDTO.getCustomColors());

        String strategyStr = JSON.toJSONString(strategyPojo);
        JSONObject strategy = JsonHelperUtil.parseObject(strategyStr);
        JSONArray executor = new JSONArray();
        executor.addAll(saveDTO.getExecutor());

        JSONObject samplingRange = saveDTO.getSamplingRange();

        entity.setTriggerCondition(triggerCondition);
        entity.setStrategy(strategy);
        entity.setExecutor(executor);
        entity.setCustomColors(customColors);
        entity.setSamplingRange(samplingRange);



        // 5.save
        try {
            dataWarningModel.save(entity);
        } catch (Exception e) {
            LOG.error("数据预警保存失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 6.如果编辑触发条件修改了，之前的数据预警历史要失效
        if (!isAdd && checkTriggerChange(new DataWarningSavePojo(){{BeanUtils.copyProperties(saveDTO,this);}})){
            invalidBatch(saveDTO.getCorpid(),new ArrayList<Long>(){{add(entity.getId());}});
        }


        // 7.日志
        String loginUserName = saveDTO.getLoginUserName();
        OperateTypeEnum operateTypeEnum = isAdd ? OperateTypeEnum.NEW : OperateTypeEnum.EDIT;
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_DATA_WARNING), loginUserName + operateTypeEnum.getName(), entity.getName());
        if (isAdd) {
            OperateLogEntity logEntity = new OperateLogEntity(corpid, saveDTO.getUserId(), loginUserName, OperateModuleTypeEnum.DATA_WARNING,
                    operateTypeEnum, entity.getId().toString(), ControlCenterMenuEnum.DATA_CENTER.getName(), memo, saveDTO.getHttpHeader(), null);
            operateLogModel.insert(logEntity);
        } else {
            JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldEntity));
            JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(entity));
            // 触发条件
            List<DetailLogPojo> detailArr = logHelp.detailLog4DataWarning(corpid, oldObj, newObj, JSONArray.parseArray(JSON.toJSONString(saveDTO.getOldTriggerCondition())), JSONArray.parseArray(JSON.toJSONString(saveDTO.getNewTriggerCondition())));
            mongoLogHelp.buildLog4DetailArr(detailArr, corpid, saveDTO.getUserId(), loginUserName, OperateModuleTypeEnum.DATA_CENTER, OperateTypeEnum.EDIT, id.toString(), entity.getName(), memo, saveDTO.getHttpHeader());
        }

        dataWarningSaveVO.setId((entity.getId()).intValue());
        return dataWarningSaveVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataWarningEnableVO enable(DataWarningEnableDTO enableDTO) throws XbbException {
        DataWarningEnableVO enableVO = new DataWarningEnableVO();

        String corpid = enableDTO.getCorpid();
        // 校验，是否是旗舰版
        if (!isUltimate(corpid)){
            return enableVO;
        }
        Integer enable = enableDTO.getEnable();
        boolean isEnable = BasicConstant.IS_USE.equals(enable);

        // 1.校验传过来的id是否能查到数据预警entity
        DataWarningEntity entity = dataWarningModel.getByKey(enableDTO.getId(), corpid);
        if (entity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
        }

        // 2.日志用到的str
        String enableStr = isEnable ? PaasConstant.ENABLE_DATA_WARNING :PaasConstant.CLOSE;
        if (Objects.equals(entity.getEnable(),enable)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }

        // 3.校验
        if (isEnable) {
            // 当前启用的数量
            int count = dataWarningModel.getCountByChartId(entity.getChartId(),1);
            if (count >= PaasConstant.DATA_WARNING_MAX_CREATE_NUM ){
                throw new XbbException(ChartErrorCodeEnum.API_ERROR_1500004, String.format(ChartErrorCodeEnum.API_ERROR_1500004.getMsg(),String.valueOf(PaasConstant.DATA_WARNING_MAX_ENABLE_NUM)));
            }

        }

        // 4.update
        entity.setEnable(enableDTO.getEnable());
        entity.setUpdateTime((long) DateUtil.getInt());
        try {
            dataWarningModel.update(entity);
        } catch (Exception e) {
            LOG.error("数据预警" + enableStr + "失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 5.日志
        String loginUserName = enableDTO.getLoginUserName();
        OperateTypeEnum operateTypeEnum = enable.equals(BasicConstant.NO_USE) ? OperateTypeEnum.CLOSE : OperateTypeEnum.ENABLE;
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_DATA_WARNING_ENABLE), loginUserName + enableStr, entity.getName());
        OperateLogEntity logEntity = new OperateLogEntity(corpid, enableDTO.getUserId(), loginUserName, OperateModuleTypeEnum.DATA_CENTER,
                operateTypeEnum, entity.getId().toString(), entity.getName(), memo, enableDTO.getHttpHeader(), null);
        operateLogModel.insert(logEntity);

        return enableVO;
    }

    @Override
    public DataWarningDelVO delete(DataWarningDelDTO dataWarningDelDTO) throws XbbException {
        DataWarningDelVO dataWarningDelVO = new DataWarningDelVO();

        Long id = dataWarningDelDTO.getId();
        String corpid = dataWarningDelDTO.getCorpid();

        // 校验，是否是旗舰版
        if (!isUltimate(corpid)){
            return dataWarningDelVO;
        }
        // 1.校验传过来的id是否能查到数据预警entity
        DataWarningEntity entity = dataWarningModel.getByKey(id, corpid);
        if (entity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
        }

        // 2.delete
        try {
            dataWarningModel.deleteByKey(id, corpid);
            // 相关的数据预警历史失效
            invalidBatch(corpid,new ArrayList<Long>(){{add(entity.getId());}});
        } catch (Exception e) {
            LOG.error("数据预警删除失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 3.日志
        String loginUserName = dataWarningDelDTO.getLoginUserName();
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), loginUserName , OperateModuleTypeEnum.DATA_WARNING.getName(), entity.getName());
        OperateLogEntity logEntity = new OperateLogEntity(corpid, dataWarningDelDTO.getUserId(), loginUserName, OperateModuleTypeEnum.DATA_CENTER,
                OperateTypeEnum.DELETE, entity.getId().toString(),entity.getName(), memo, dataWarningDelDTO.getHttpHeader(), null);
        operateLogModel.insert(logEntity);
        dataWarningDelVO.setId(id.intValue());
        return dataWarningDelVO;
    }

    @Override
    public void batchAddOrUpdate(DataWarningBatchDTO batchDTO) throws XbbException {
        // 校验，是否是旗舰版
        if (!isUltimate(batchDTO.getCorpid())){
            return;
        }
        List<DataWarningSavePojo> dataWarningSavePojoList = batchDTO.getDataWarningSavePojoList();
        // 1.声明批量增加和修改的list
        List<DataWarningEntity> insertList = new ArrayList<>();
        List<DataWarningEntity> updateList = new ArrayList<>();
        List<DataWarningEntity> enableList = new ArrayList<>();
        List<DataWarningEntity> deleteList = new ArrayList<>();
        List<DataWarningEntity> updateForLogList = new ArrayList<>();
        List<DataWarningEntity> deleteForLogList = new ArrayList<>();
        // 如果更改了触发器，要让之前的触发历史失效
        List<Long> ids = new ArrayList<>();

        // 2.将dataWarningSavePojoList里面的数据分为增加和修改
        if (dataWarningSavePojoList.size()>0){
            // 如果operationFlag为0为增加,1为修改，2为删除
            dataWarningSavePojoList.forEach(pojo ->{
                if (Objects.equals(DwOperationFlagEnum.ADD.getCode(),pojo.getOperationFlag())){
                    insertList.add(new DataWarningEntity(){{
                        BeanUtil.copyProperties(pojo, this);
                        setCorpid(batchDTO.getCorpid());
                        long now = DateTimeUtil.getInt();
                        setTriggerCondition(new JSONArray(){{addAll(pojo.getTriggerCondition());}});
                        setStrategy(JsonHelperUtil.parseObject(JSON.toJSONString(pojo.getStrategy())));
                        setExecutor(new JSONArray(){{addAll(pojo.getExecutor());}});
                        if (Objects.nonNull(pojo.getCustomColors())){
                            setCustomColors(new JSONArray(){{addAll(pojo.getCustomColors());}});
                        }
                        setAddTime(now);
                        setUpdateTime(now);
                    }});
                }else if (Objects.equals(DwOperationFlagEnum.EDIT.getCode(),pojo.getOperationFlag())){
                    DataWarningEntity dataWarningEntity = new DataWarningEntity(){{
                        BeanUtil.copyProperties(pojo, this);
                        setCorpid(batchDTO.getCorpid());
                        if (Objects.nonNull(pojo.getTriggerCondition())){
                            setTriggerCondition(new JSONArray(){{addAll(pojo.getTriggerCondition());}});
                        }
                        if (Objects.nonNull(pojo.getStrategy())){
                            setStrategy(JsonHelperUtil.parseObject(JSON.toJSONString(pojo.getStrategy())));
                        }
                        if (Objects.nonNull(pojo.getExecutor())){
                            setExecutor(new JSONArray(){{addAll(pojo.getExecutor());}});
                        }
                        if (Objects.nonNull(pojo.getCustomColors())){
                            setCustomColors(new JSONArray(){{addAll(pojo.getCustomColors());}});
                        }
                        setUpdateTime(DateTimeUtil.getInt());
                        setTriggerNum(null);
                    }};
                    if (Objects.nonNull(dataWarningEntity.getTriggerCondition())){
                        updateList.add(dataWarningEntity);
                        // 判断触发条件是否改变
                        if (checkTriggerChange(pojo)){
                            ids.add(pojo.getId());
                        }
                    } else {
                        enableList.add(dataWarningEntity);
                    }
                    updateForLogList.add(dataWarningEntity);

                }else if (Objects.equals(DwOperationFlagEnum.DEL.getCode(),pojo.getOperationFlag())){
                    DataWarningEntity dataWarningEntity = new DataWarningEntity(){{
                        BeanUtil.copyProperties(pojo, this);
                        setCorpid(batchDTO.getCorpid());
                        setDel(1);
                        setUpdateTime(DateTimeUtil.getInt());
                        setTriggerNum(null);
                    }};
                    deleteList.add(dataWarningEntity);
                    deleteForLogList.add(dataWarningEntity);

                    ids.add(pojo.getId());
                }
            });

        }

        // 3.insert 和 update
        try {
            if (insertList.size()>0){
                dataWarningModel.insertBatch(insertList);
            }
            if (updateList.size()>0){
                dataWarningModel.updateBatch(updateList,batchDTO.getCorpid());
            }
            if (enableList.size()>0){
                dataWarningModel.updateBatch(enableList,batchDTO.getCorpid());
            }
            if (deleteList.size()>0){
                dataWarningModel.updateBatch(deleteList,batchDTO.getCorpid());
            }
        } catch (Exception e) {
            LOG.error("数据预警更新失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 4.触发历史失效
        if (ids.size()>0){
            invalidBatch(batchDTO.getCorpid(),ids);
        }

        // TODO 5.日志后面要做成异步
        String loginUserName = batchDTO.getLoginUserName();
        String corpid = batchDTO.getCorpid();
        String userId = batchDTO.getUserId();
        String httpHeader = batchDTO.getHttpHeader();
        dwBatchLog(loginUserName,corpid,userId,insertList,OperateTypeEnum.NEW,httpHeader);
        dwBatchLog(loginUserName,corpid,userId,insertList,OperateTypeEnum.EDIT,httpHeader);
        dwBatchLog(loginUserName,corpid,userId,insertList,OperateTypeEnum.DELETE,httpHeader);

    }

    /**
     * 批量日志
     * @param loginUserName
     * @param corpid
     * @param userId
     * @param list
     * @param operateTypeEnum
     * @param httpHeader
     * @throws XbbException
     */
    public void dwBatchLog(String loginUserName,String corpid,String userId,List<DataWarningEntity> list,OperateTypeEnum operateTypeEnum,String httpHeader) throws XbbException {
        for (DataWarningEntity entity : list) {
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_DATA_WARNING), loginUserName + operateTypeEnum.getName(), entity.getName());
            OperateLogEntity logEntity = new OperateLogEntity(corpid, userId, loginUserName, OperateModuleTypeEnum.DATA_CENTER,
                    operateTypeEnum, entity.getId().toString(),entity.getName(), memo, httpHeader, null);
            operateLogModel.insert(logEntity);
        }
    }

    @Override
    public void invalidBatch(String corpid, List<Long> invalidList) throws XbbException {
        if (Objects.nonNull(invalidList) && !invalidList.isEmpty()) {
            List<Long> allDataIdList = new ArrayList<>(invalidList);
            int count = allDataIdList.size();
            int start = 0;
            int pageNum = 2000;
            for (; start <= count; start = start + pageNum) {
                // 分组数据的endIndex
                int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                List<Long> dataIds = allDataIdList.subList(start, endIndex);
                dataWarningHistoryModel.invalidBatch(corpid, dataIds);
            }
        }
    }

    @Override
    public DataWarningQueryListVO queryByChartId(DataWarningQueryDTO queryDTO) throws XbbException {
        // 校验，是否是旗舰版
        if (!isUltimate(queryDTO.getCorpid())){
            return new DataWarningQueryListVO(){{setDataWarningQueryVOList(new ArrayList<>());}};
        }
        List<DataWarningQueryVO> queryVOList = new ArrayList<>();
        // 查询出此图表id的所有预警
        List<DataWarningEntity> entityList = dataWarningModel.queryByChartId(queryDTO.getCorpid(),queryDTO.getChartId());
        for (DataWarningEntity entity : entityList) {
            List<DwHistoryDataPojo> dwHistoryDataPojoList = new ArrayList<>();
            queryVOList.add(new DataWarningQueryVO(){{
                BeanUtils.copyProperties(entity,this);
                // 此预警的历史记录（多少天根据用户在预警设置里面的来）
                List<DwHistoryDataPojo> historyDataPojoList = queryByDataWarningId(getCorpid(),getId(),entity.getHistoryMaxNum());
                setDwHistoryDataList(historyDataPojoList);
                dwHistoryDataPojoList.addAll(historyDataPojoList);
            }});
        }
        return new DataWarningQueryListVO(){{setDataWarningQueryVOList(queryVOList);}};
    }

    /**
     * 单个预警的historyMaxNum条历史记录
     * @param corpid
     * @param dataWarningId
     * @param historyMaxNum
     * @return
     */
    private List<DwHistoryDataPojo> queryByDataWarningId(String corpid, Long dataWarningId, Integer historyMaxNum) {
        List<DataWarningHistoryEntity> entityList = dataWarningHistoryModel.queryByDataWarningId(corpid,dataWarningId,historyMaxNum);
        List<DwHistoryDataPojo> pojoList = new ArrayList<>();
        int num = 0;
        for (DataWarningHistoryEntity entity:entityList) {
            if( num ++ < historyMaxNum){
                DwHistoryDataPojo dataPojo = JSON.parseObject((entity.getData().toJSONString()), DwHistoryDataPojo.class);
                pojoList.add(dataPojo);
            }
            if (num == historyMaxNum){
                break;
            }
        }
        return pojoList;
    }

    @Override
    public DataWarningListVO list(DataWarningListDTO dataWarningListDTO) throws XbbException {
        DataWarningListVO dataWarningListVO = new DataWarningListVO();
        // 校验，是否是旗舰版
        if (!isUltimate(dataWarningListDTO.getCorpid())){
            return new DataWarningListVO(){{setPageHelper(PageHelperUtil.initPageHelper(0,dataWarningListDTO.getPage(),dataWarningListDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE));}};
        }
        // 根据图表的chartNameLike查询出图表的id和categoryId和name
        ChartInfoDwVO chartListForDwVO = chartService.chartList4Dw(new ChartListDwDTO(){{
            setCorpid(dataWarningListDTO.getCorpid());
            setUserId(dataWarningListDTO.getUserId());
            setPlatform(dataWarningListDTO.getPlatform());
            setHttpHeader(dataWarningListDTO.getHttpHeader());
            setLoginUser(dataWarningListDTO.getLoginUser());
            setLoginUserName(dataWarningListDTO.getLoginUserName());
            setNameLike(dataWarningListDTO.getChartNameLike());
            setFilterPermission(true);
        }});
        List<ChartInfoDwPojo> chartInfoDwPojoList = chartListForDwVO.getChartInfoDwPojoList();
        if (null == chartInfoDwPojoList || chartInfoDwPojoList.size() == 0 ) {
            return new DataWarningListVO(){{setList(new ArrayList<>());setPageHelper(PageHelperUtil.initPageHelper(0,dataWarningListDTO.getPage(),dataWarningListDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE));}};
        }
        Map<Long,ChartInfoDwPojo> chartIdMap = chartInfoDwPojoList.stream().collect(Collectors.toMap(ChartInfoDwPojo::getId,entity ->entity));

        // 查出所有用户能看到的图表的相关数据预警
        Map<String, Object> param = BeanUtil.convertBean2Map(dataWarningListDTO);
        param.remove("triggerNum");
        param.put(StringConstant.CORPID, dataWarningListDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("chartIdIn",chartIdMap.keySet());
        param.put("orderByStr","last_trigger_time DESC");
        param.put("nameLike",dataWarningListDTO.getNameLike());
        // 触发次数模糊查询
        if (Objects.nonNull(dataWarningListDTO.getSymbol()) && CollectionUtils.isNotEmpty(dataWarningListDTO.getTriggerNum())){
            ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(dataWarningListDTO.getSymbol());
            List<Integer> triggerNum = dataWarningListDTO.getTriggerNum();
            Integer firstTriggerNum = triggerNum.get(0);
            switch (conditionEnum){
                case GREATEREQUAL:
                    param.put("triggerNumGreaterEqual",firstTriggerNum);
                    break;
                case GREATERTHAN:
                    param.put("triggerNumGreaterThan",firstTriggerNum);
                    break;
                case LESSTHAN:
                    param.put("triggerNumLessThan",firstTriggerNum);
                    break;
                case LESSEQUAL:
                    param.put("triggerNumLessEqual",firstTriggerNum);
                    break;
                case RANGE:
                    if (triggerNum.size() == PaasConstant.RANGE_SIZE){
                        param.put("triggerNumRangeLeft",firstTriggerNum);
                        param.put("triggerNumRangeRight",triggerNum.get(1));
                    }
                    break;
                default:
                    break;
            }
        }
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param,dataWarningModel,dataWarningListDTO.getPageSize());
        List<DataWarningEntity> dataWarningEntityList = (List<DataWarningEntity>) PageHelperUtil.getEntityList(param,pageHelper,dataWarningModel);

        // 加载数据
        List<DataWarningPojo> list = new ArrayList<>();
        for (DataWarningEntity item : dataWarningEntityList) {
            DataWarningPojo pojo = new DataWarningPojo() {{
                setId(item.getId());
                setEnable(item.getEnable());
                setName(item.getName());
                setChartId(item.getChartId());
                // 加载图表相关的信息
                ChartInfoDwPojo chartInfoDwPojo;
                if (null != (chartInfoDwPojo = chartIdMap.get(item.getChartId()))) {
                    setCategoryId(chartInfoDwPojo.getCategoryId());
                    setChartName(chartInfoDwPojo.getName());
                    // 图表穿透权限
                    setChartCenterPermission(chartInfoDwPojo.getChartCenterPermission());
                    setCategoryVisiblePermission(chartInfoDwPojo.getCategoryVisiblePermission());
                    setChartVisiblePermission(chartInfoDwPojo.getChartVisiblePermission());
                }
            }};
            pojo.setLastTriggerTime(item.getLastTriggerTime());
            // 加载触发历史的次数
            if (null != item.getTriggerNum() && item.getTriggerNum()>0){
                pojo.setTriggerHistory("已经触发了" + item.getTriggerNum() + "次");
            } else {
                if(checkZeroInTriggerNum(dataWarningListDTO.getSymbol(),dataWarningListDTO.getTriggerNum()) )
                {
                    pojo.setTriggerHistory("已经触发了0次");
                }
            }
            list.add(pojo);
        }
//        Collections.sort(list, (o1, o2) -> {
//            if (null == o1.getLastTriggerTime() && null == o2.getLastTriggerTime()){
//                return 1;
//            }else if (null == o1.getLastTriggerTime()){
//                return 1;
//            }else if (null == o2.getLastTriggerTime()){
//                return -1;
//            }else {
//                return o2.getLastTriggerTime().compareTo(o1.getLastTriggerTime());
//            }
//        });
        dataWarningListVO.setList(list);
        dataWarningListVO.setPageHelper(pageHelper);
        return dataWarningListVO;
    }

    /**
     * 是否触发0次
     * @param symbol
     * @param triggerNum
     * @return
     */
    boolean checkZeroInTriggerNum(String symbol,List<Integer> triggerNum){
        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
        if (Objects.isNull(symbol) || symbol.isEmpty() || Objects.isNull(triggerNum) || triggerNum.size()<1){
            return true;
        }
        switch (conditionEnum){
            case GREATEREQUAL:
                if (triggerNum.get(0).compareTo(0)<=0){
                    return true;
                }
                break;
            case GREATERTHAN:
                if (triggerNum.get(0).compareTo(0)<0){
                    return true;
                }
                break;
            case LESSTHAN:
                if (triggerNum.get(0).compareTo(0)>=0){
                    return true;
                }
                break;
            case LESSEQUAL:
                if (triggerNum.get(0).compareTo(0)>0){
                    return true;
                }
                break;
            case RANGE:
                if (triggerNum.size()>1 && triggerNum.get(0).compareTo(0)<0 && triggerNum.get(1).compareTo(0)>0) {
                    return true;
                }
                break;
            default:
                return false;
        }
        return false;
    }
    @Override
    public DwHistoryListVO warningDetails(DataWarningDetailsDTO dataWarningDetailsDTO) throws XbbException {
        // 校验，是否是旗舰版
        if (!isUltimate(dataWarningDetailsDTO.getCorpid())){
            return new DwHistoryListVO(){{setDwHistoryDetailsPojoList(new ArrayList<>());setPageHelper(PageHelperUtil.initPageHelper(0,dataWarningDetailsDTO.getPage(),dataWarningDetailsDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE));}};
        }
        Map<String, Object> param = BeanUtil.convertBean2Map(dataWarningDetailsDTO);
        param.put(StringConstant.CORPID, dataWarningDetailsDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("trigger_invalid",0);
        param.put("orderByStr","update_time desc");
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param, dataWarningHistoryModel, dataWarningDetailsDTO.getPage(),dataWarningDetailsDTO.getPageSize());
        List<DataWarningHistoryEntity> historyEntityList = (List<DataWarningHistoryEntity>) PageHelperUtil.getEntityList(param, pageHelper, dataWarningHistoryModel);
        List<DwHistoryDetailsPojo> dwHistoryDetailsPojoList = new ArrayList<>();
        for (DataWarningHistoryEntity item : historyEntityList) {
            DwHistoryDataPojo dataPojo = JSON.parseObject(item.getData().toJSONString(),DwHistoryDataPojo.class);
            DwHistoryDetailsPojo tempPojo = new DwHistoryDetailsPojo();
            BeanUtils.copyProperties(dataPojo, tempPojo, DwHistoryDetailsPojo.class);
            if (Objects.nonNull(dataPojo)){
                tempPojo.setTriggerConditionStr(dataPojo.getTriggerConditionStr());
            }
            dwHistoryDetailsPojoList.add(tempPojo);
        }
        if (null!=historyEntityList){
            return new DwHistoryListVO(){{setDwHistoryDetailsPojoList(dwHistoryDetailsPojoList);setPageHelper(pageHelper);}};
        }
        return new DwHistoryListVO();
    }

    @Override
    public DataWarningIndexVO get(DataWarningIndexDTO indexDTO) throws XbbException {
        DataWarningIndexVO dataWarningIndexVO = new DataWarningIndexVO();
        dataWarningIndexVO.setDataWarningIndexPojoList(new ArrayList<>());
        // 校验，是否是旗舰版
        if (!isUltimate(indexDTO.getCorpid())){
            return dataWarningIndexVO;
        }
        // 查询出图表的id和categoryId和name
        Map<Long,ChartInfoDwPojo> chartIdMap;
        ChartInfoDwVO chartListForDwVO = chartService.chartList4Dw(new ChartListDwDTO(){{
            setCorpid(indexDTO.getCorpid());
            setUserId(indexDTO.getUserId());
            setPlatform(indexDTO.getPlatform());
            setHttpHeader(indexDTO.getHttpHeader());
            setLoginUser(indexDTO.getLoginUser());
            setLoginUserName(indexDTO.getLoginUserName());
        }});
        List<ChartInfoDwPojo> chartInfoDwPojoList = chartListForDwVO.getChartInfoDwPojoList();
        if (Objects.isNull(chartInfoDwPojoList) || chartInfoDwPojoList.size() == 0){
            return dataWarningIndexVO;
        }
        chartIdMap = chartInfoDwPojoList.stream().collect(Collectors.toMap(ChartInfoDwPojo::getId,entity ->entity));

        // 加载预警历史
        Map<String, Object> param = new HashMap<String, Object>(PaasConstant.DEFAULT_INITIAL_CAPACITY){{
           put(StringConstant.CORPID, indexDTO.getCorpid());
           put(StringConstant.DEL, DelEnum.NORMAL.getDel());
           put("columns","data_warning_id,chart_id,data,add_time");
           put("chartIdIn",chartIdMap.keySet());
           put("orderByStr","add_time DESC");
//           put("groupByStr","data_warning_id");
           put("limitLen",4);
        }};
        List<DataWarningHistoryEntity> historyEntityList = dataWarningHistoryModel.findEntitys(param);
        if (historyEntityList.size() == 0){
            return dataWarningIndexVO;
        }
        List<DataWarningIndexPojo> dataWarningIndexPojoList = new ArrayList<>();

        // 加载首页数据
        historyEntityList.forEach(entity ->{
            DataWarningIndexPojo pojo = new DataWarningIndexPojo();
            pojo.setChartId(entity.getChartId());
            pojo.setDataWarningId(entity.getDataWarningId());
            // 加载预警历史data里面的数据
            DwHistoryDataPojo dataPojo = JSON.parseObject(entity.getData().toJSONString(),DwHistoryDataPojo.class);
            if (Objects.nonNull(dataPojo)){
                pojo.setTriggerConditionStr(dataPojo.getTriggerConditionStr());
                pojo.setWarnValue(dataPojo.getWarnValue());
                pojo.setWarningName(dataPojo.getWarningName());
            }
            // 加载图表相关数据
            ChartInfoDwPojo chartInfoDwPojo;
            if (Objects.nonNull(chartInfoDwPojo = chartIdMap.get(entity.getChartId()))){
                pojo.setCategoryId(chartInfoDwPojo.getCategoryId());
                pojo.setChartName(chartInfoDwPojo.getName());
                pojo.setChartCenterPermission(chartInfoDwPojo.getChartCenterPermission());
                pojo.setCategoryVisiblePermission(chartInfoDwPojo.getCategoryVisiblePermission());
                pojo.setChartVisiblePermission(chartInfoDwPojo.getChartVisiblePermission());
            }
            dataWarningIndexPojoList.add(pojo);
        });
        dataWarningIndexVO.setDataWarningIndexPojoList(dataWarningIndexPojoList);
        return dataWarningIndexVO;
    }

    @Override
    public DataWarningIndexListVO list(DataWarningIndexListDTO indexListDTO) throws XbbException {
        DataWarningIndexListVO dataWarningIndexListVO = new DataWarningIndexListVO();
        // 校验，是否是旗舰版
        if (!isUltimate(indexListDTO.getCorpid())){
            return new DataWarningIndexListVO(){{setDataWarningIndexPojoList(new ArrayList<>());setPageHelper(PageHelperUtil.initPageHelper(0,indexListDTO.getPage(),indexListDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE));}};
        }
        // 获取chartName和categoryId
        Map<Long,ChartInfoDwPojo> chartIdMap;
        ChartInfoDwVO chartListForDwVO = chartService.chartList4Dw(new ChartListDwDTO(){{
            setCorpid(indexListDTO.getCorpid());
            setUserId(indexListDTO.getUserId());
            setPlatform(indexListDTO.getPlatform());
            setHttpHeader(indexListDTO.getHttpHeader());
            setLoginUser(indexListDTO.getLoginUser());
            setLoginUserName(indexListDTO.getLoginUserName());
            setNameLike(indexListDTO.getChartNameLike());
        }});
        List<ChartInfoDwPojo> chartInfoDwPojoList = chartListForDwVO.getChartInfoDwPojoList();
        if (Objects.isNull(chartInfoDwPojoList) || chartInfoDwPojoList.size() == 0){
            dataWarningIndexListVO.setPageHelper(new PageHelper());
            return dataWarningIndexListVO;
        }
        chartIdMap = chartInfoDwPojoList.stream().collect(Collectors.toMap(ChartInfoDwPojo::getId,entity ->entity));

        // 获取预警历史，根据时间倒叙
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, indexListDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("orderByStr","update_time desc");
        if (Objects.nonNull(indexListDTO.getNameLike())){
            param.put("warningName",indexListDTO.getNameLike());
        }
        param.put("chartIdIn",chartIdMap.keySet());
        // 触发条件筛选
        if (Objects.nonNull(indexListDTO.getSymbol()) && CollectionUtils.isNotEmpty(indexListDTO.getTriggerTime())){
            // 触发历史里面的triggerTime和add时间一样
            ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(indexListDTO.getSymbol());
            List<Long> triggerTime = indexListDTO.getTriggerTime();
            Long firstTriggerTime = triggerTime.get(0);
            switch (conditionEnum){
                case GREATEREQUAL:
                    param.put("triggerTimeGreaterEqual",firstTriggerTime);
                    break;
                case GREATERTHAN:
                    param.put("triggerTimeGreaterThan",firstTriggerTime);
                    break;
                case LESSTHAN:
                    param.put("triggerTimeLessThan",firstTriggerTime);
                    break;
                case LESSEQUAL:
                    param.put("triggerTimeLessEqual",firstTriggerTime);
                    break;
                case RANGE:
                    if (indexListDTO.getTriggerTime().size() == PaasConstant.RANGE_SIZE) {
                        param.put("triggerTimeRangeLeft",firstTriggerTime);
                        param.put("triggerTimeRangeRight",triggerTime.get(0));
                    }
                    break;
                default:
                    break;
        }
        }
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param, dataWarningHistoryModel, indexListDTO.getPage(),indexListDTO.getPageSize());
        List<DataWarningHistoryEntity> historyEntityList = (List<DataWarningHistoryEntity>) PageHelperUtil.getEntityList(param, pageHelper, dataWarningHistoryModel);

        // 加载返回数据
        List<DataWarningIndexPojo> dataWarningIndexPojoList = new ArrayList<>();
        for (DataWarningHistoryEntity item : historyEntityList) {
            DwHistoryDataPojo dataPojo = JSON.parseObject(item.getData().toJSONString(),DwHistoryDataPojo.class);
            DataWarningIndexPojo indexPojo = new DataWarningIndexPojo(){{
                setDataWarningId(item.getDataWarningId());
                setTriggerTime(dataPojo.getTriggerTime());
                setChartId(item.getChartId());
            }};
            // 预警历史的data不为空，设置相应的触发条件，时间和值已经当时的预警设置名称
            if (Objects.nonNull(dataPojo)){
                indexPojo.setTriggerConditionStr(dataPojo.getTriggerConditionStr());
                indexPojo.setTriggerTime(dataPojo.getTriggerTime());
                indexPojo.setWarnValue(dataPojo.getWarnValue());
                indexPojo.setWarningName(dataPojo.getWarningName());
            }

            // 加载图表相关的信息
            ChartInfoDwPojo chartInfoDwPojo;
            if (Objects.nonNull(chartInfoDwPojo = chartIdMap.get(item.getChartId()))){
                indexPojo.setCategoryId(chartInfoDwPojo.getCategoryId());
                indexPojo.setChartName(chartInfoDwPojo.getName());
                // 权限用于判断是否能穿透到图表中心
                indexPojo.setChartCenterPermission(chartInfoDwPojo.getChartCenterPermission());
                indexPojo.setCategoryVisiblePermission(chartInfoDwPojo.getCategoryVisiblePermission());
                indexPojo.setChartVisiblePermission(chartInfoDwPojo.getChartVisiblePermission());
            }
            dataWarningIndexPojoList.add(indexPojo);
        }
        dataWarningIndexListVO.setDataWarningIndexPojoList(dataWarningIndexPojoList);
        dataWarningIndexListVO.setPageHelper(pageHelper);
        return dataWarningIndexListVO;
    }

    @Override
    public DataWarningRemindVO remind(DataWarningRemindDTO dataWarningRemindDTO) throws XbbException {
        DataWarningRemindVO dataWarningRemindVO = new DataWarningRemindVO();
        // 校验，是否是旗舰版
        if (!isUltimate(dataWarningRemindDTO.getCorpid())){
            dataWarningRemindVO.setIsRemind(false);
            return dataWarningRemindVO;
        }
        Integer count = dataWarningHistoryModel.getTodayExecutedCount(dataWarningRemindDTO.getCorpid());
        CompanyEntity companyEntity = companyModel.getByKey(dataWarningRemindDTO.getCorpid());
        Integer feeType;
        Integer executeNumber;
        if (null != companyEntity){
            feeType = companyEntity.getFeeType();
            if (Objects.equals(feeType,PackageTypeEnum.ADVANCED.getType()) || Objects.equals(feeType,PackageTypeEnum.ULTIMATE.getType())){
                executeNumber = Objects.equals(feeType, PackageTypeEnum.ADVANCED.getType())?PaasConstant.ADVANCED_NUMBER_EXECUTIONS:PaasConstant.ULTIMATE_NUMBER_EXECUTIONS;
                if (count >= executeNumber){
                    dataWarningRemindVO.setIsRemind(true);
                }
            }
        }
        return dataWarningRemindVO;
    }

    @Override
    public DwExecutedRemindVO executedRemind(DwExecutedRemindDTO remindDTO) throws XbbException {
        // 校验，是否是旗舰版
        if (!isUltimate(remindDTO.getCorpid())){
            return new DwExecutedRemindVO();
        }
        CompanyEntity companyEntity = companyModel.getByKey(remindDTO.getCorpid());
        Integer feeType;
        Integer totalNumber;
        if (null != companyEntity){
            feeType = companyEntity.getFeeType();
            if (Objects.equals(feeType,PackageTypeEnum.ADVANCED.getType()) || Objects.equals(feeType,PackageTypeEnum.ULTIMATE.getType())){
                totalNumber = Objects.equals(feeType, PackageTypeEnum.ADVANCED.getType())?PaasConstant.ADVANCED_NUMBER_EXECUTIONS:PaasConstant.ULTIMATE_NUMBER_EXECUTIONS;
                Integer count = dataWarningHistoryModel.getTodayExecutedCount(remindDTO.getCorpid());
                return new DwExecutedRemindVO(){{setExecuted(count);setTotalNumber(totalNumber);}};
            }
        }
        return new DwExecutedRemindVO();
    }


    /**
     * 设置执行设置可选项列表
     *
     * @param getVO        前端需要数据
     * @return
     * @throws
     * @author mengna.deng
     * @date: 2021/4/15 19:47
     * @version v1.0
     * @since v1.0
     */
    private void strategyConditionList(DataWarningGetVO getVO) {
        // 执行设置可选项：执行动作，执行策略，自定义策略，执行日期（周），占位符
        List<ItemDataPoJo> actionArray = new ArrayList<>();
        // 消息
        ItemDataPoJo messagePojo = new ItemDataPoJo(ActionTypeEnum.MESSAGE.getMemo(), ActionTypeEnum.MESSAGE.getCode());
        // 短信
//        ItemDataPoJo smsPojo = new ItemDataPoJo(ActionTypeEnum.SMS.getMemo(), ActionTypeEnum.SMS.getCode());
        actionArray.add(messagePojo);

        // 执行策略
        List<ItemDataPoJo> strategyTypeArray = new ArrayList<>();
        List<DataWarningStrategyTypeEnum> strategyTypeEnumList = DataWarningStrategyTypeEnum.getAllEnum();
        strategyTypeEnumList.forEach(item -> {
            ItemDataPoJo pojo = new ItemDataPoJo(item.getMemo(), item.getCode());
            strategyTypeArray.add(pojo);
        });
        List<ItemDataPoJo> strategyWeekArray = new ArrayList<>();
        List<WeekEnum> weekEnumList = WeekEnum.getAllEnum();
        weekEnumList.forEach(item -> {
            ItemDataPoJo pojo = new ItemDataPoJo(item.getName(), item.getCode());
            strategyWeekArray.add(pojo);
        });

        getVO.setActionArray(actionArray);
        getVO.setStrategyTypeArray(strategyTypeArray);
        getVO.setStrategyWeekArray(strategyWeekArray);
    }

    /**
     * 预警的触发条件是否改变
     * @param savePojo
     * @return
     */
    private boolean checkTriggerChange(DataWarningSavePojo savePojo){
        List<DwTriggerConditionPojo> oldTriggerCondition = savePojo.getOldTriggerCondition();
        List<DwTriggerConditionPojo> newTriggerCondition = savePojo.getNewTriggerCondition();
        DwTriggerConditionPojo oldTriggerConditionPojo = new DwTriggerConditionPojo();
        DwTriggerConditionPojo newTriggerConditionPojo = new DwTriggerConditionPojo();
        if (Objects.nonNull(oldTriggerCondition) && oldTriggerCondition.size()>0){
            oldTriggerConditionPojo = oldTriggerCondition.get(0);
        }
        if (Objects.nonNull(newTriggerCondition) && newTriggerCondition.size()>0){
            newTriggerConditionPojo = newTriggerCondition.get(0);
        }
        if (!Objects.equals(oldTriggerConditionPojo,newTriggerConditionPojo)){
            return true;
        }
        return false;
    }

    private Boolean isUltimate(String corpid) throws XbbException {
        Integer feeType = packageHelp.getFeeType(corpid);
        if (Objects.equals(feeType,PackageTypeEnum.ULTIMATE.getType())){
            return true;
        }
        return false;
    }

    @Override
    public void dwMessageAdd(DataWarningMessageAddDTO dataWarningMessageAddDTO) {
        try {
            for (MessageRabbitMqDTO mq : dataWarningMessageAddDTO.getMessageRabbitMqDTOList()) {
                baseProducer.sendMessage(PushTypeEnum.DATA_WARNING_PUSH, mq);
            }
        }catch (XbbException e) {
            LOG.error("数据预警消息推送失败");
        }
    }
}